export default function pubsub() {
  let topics = {}, subUid = -1;
  function publish(topic, args) {
    if (!topics[topic]) {
      return false;
    }
    setTimeout(function () {
      let subscribers = topics[topic];
      let len = subscribers? subscribers.length: 0;
      while(len--) {
        subscribers[len].func(args);
      }
    }, 0);
    return true;
  }
  function subscribe(topic, func) {
    const token = '' + (++subUid);
    if (!topics[topic]) {
      topics[topic] = [];
    }
    topics[topic].push({
      token,
      func
    });
    return token;
  }
  function unsubscribe(token) {
    for (let m in topics) {
      if (topics[m]) {
        for (let i = 0, j = topics[m].length; i < j; i++) {
          if (topics[m][i].token === token) {
            topics[m].splice(i, 1);
            return token;
          }
        }
      }
    }
    return false;
  }
  return { publish, subscribe, unsubscribe };
}
